$(function() {
	"use strict";

    var e = getCookie("key");
    var inviter_name = getCookie("inviter_name");
    var member_type = getUserType();
    if(member_type == ''){
        member_type = 3;
    }
    console.log(member_type);

    // 用户验证
    // function memberCheck() {
    //     if(!checkLoginStatus()) return;
    //     baseApi.get( "Member/index", function(result) {
    //         if(!result.store_info || result.store_info.inviter_state != 1){
    //             pageChange("../mall/opening_gift_bag_list.html?inviter_id="+ getCookie('inviter_id'));
    //             return;
    //         }
	//         inviter_name = result.store_info.inviter_name;
    //     });
    // }

    $('body').on('tap', '.home-category .toggle', function(){
        if($(this).hasClass('active')){
            $(this).removeClass('active')
            $('.category-nav').removeClass('active')
        }else{
            $(this).addClass('active')
            $('.category-nav').addClass('active')
        }
    });

    function loadTimePeriod(time_begin) {
    	var thisObj = $('.time-group-item[data-time_begin="'+time_begin+'"]');
    	var timeGroupObj = $('.time-group');

    	$('.time-group-item').removeClass('time-active');
	    thisObj.addClass('time-active');
	    var time_end = thisObj.data('time_end');
	    // 首次加载，自动滚动
	    if(!window.defaultTimePeriodT) {
	    	console.log(window.defaultTimePeriodT);
		    timeGroupObj.scrollLeft(timeGroupObj.scrollLeft() + thisObj.position().left - 160);
	    }

	    if(window.nextTimePeriod) {
		    if(window.nextTimePeriodT) {
			    // 清除定时
			    clearTimeout(window.nextTimePeriodT);
		    }

		    window.todayTimePeriodT = new Date().getTime();
		    // 下一个时段刷新页面
		    window.nextTimePeriodT = setTimeout(function () {
		    	// 时段重置
		    	window.timePeriodReset = true;
		    	if(new Date(window.defaultTimePeriodT).getDay() !== new Date(window.todayTimePeriodT).getDay()) {
		    		pageLoad(); // 页面重新加载（跨天）
			    } else {
				    timePeriodInit();   // 只跳转时段
			    }
		    }, window.nextTimePeriod * 1000 - new Date().getTime());
	    }

	    // 记录当前时段
	    window.defaultTimePeriodT = time_begin;

	    // 商品查询
	    // 初始化加载
	    var html = '    <div class="sctouch-norecord search">\n' +
		    '        <div class="norecord-ico"><i class="iconfont"></i></div>\n' +
		    '        <dl>\n' +
		    '            <dt>数据加载中...</dt>\n' +
		    '        </dl>\n' +
		    '    </div>';
	    $('.goods-list').html(html);

	    if(window.notFirstLoad) {
		    // 页面滚动到顶部
		    $('html,body').scrollTop($('.item-goods').offset().top - $('#header').height() - (localCache('STATUS_BAR_HEIGHT') || 0));
	    } else {
		    window.notFirstLoad = true;
	    }

	    $.getJSON(ApiUrl + "/goods/goods_list.html", {
		    time_begin: time_begin,
		    time_end: time_end,
		    key: getCookie('key')
	    }, function (data) {
	        data.result.member_type =  member_type;
            console.log(data);
		    var html = template('goods_list', data);
		    $('.item-goods .goods-list').html(html);
	    });
    }

    // 时间轴点击
    $('body').on('tap', '.time-group-item', function () {
		loadTimePeriod($(this).data('time_begin'));
    });

    // 记录页面滚动位置
    $(window).scroll(function (e) {
        window.windowScrollTop = Math.max($('html').scrollTop(), $('body').scrollTop());
        let opcity = Math.min(1, window.windowScrollTop/250);
        // 滚动监控顶部
	    $('.sctouch-home-top').css({
		    background: 'rgba(234, 49, 35, '+opcity+')'
	    });
    });

    // 初始时段
    function timePeriodInit() {

        var defaultTimeGroupItem;
        // 时段不需要重设
        if(!window.timePeriodReset) {
            defaultTimeGroupItem = $('.time-group-item[data-time_begin="'+window.defaultTimePeriodT+'"]');
            let timeGroup = $('.time-group');
            timeGroup.scrollLeft(window.timePeriodScrollLeft);
        } else {
            //首次加载初始化为当前时段 今天
            defaultTimeGroupItem = $('.today.time-group-item').eq(0);

	        let nowDate =Date.parse(new Date()) / 1000;
            $('.today.time-group-item').each(function () {
                var begin_time = $(this).attr("data-time_begin");
                var end_time = $(this).attr("data-time_end");
                if (nowDate > begin_time && nowDate < end_time) {
                    defaultTimeGroupItem = $(this);
                    window.nextTimePeriod = $(this).next('.time-group-item').data('time_begin');        // 下一个时段记录
                }
            });
        }

	    window.timePeriodReset = false;
        window.defaultTimePeriodT = null;

        // 初始化滚动条位置
        $('html, body').scrollTop(window.windowScrollTop || 0);

        loadTimePeriod(defaultTimeGroupItem.data('time_begin'));
    }
    //消息通知
    function message() {
        baseApi.post("/Shop/message_num",
            function (e) {
        	    var noticeDot = $('#header .msg .notice');
        	    if(noticeDot.length === 0) {
		            noticeDot = $('<em class="notice"></em>');
		            $('#header .msg i').before(noticeDot);
	            }
                if(e > 0){
                	noticeDot.show();
                } else {
                	noticeDot.hide();
                }
            })
    }

    function pageLoad() {
        message();
        $.ajax({
            url: ApiUrl + "/index/app",
            type: 'get',
            dataType: 'json',
            success: function(result) {
                var data = result.result;
                //goodsclass
                var html = '';
                $.each(data,function(k, v) {
                    switch (k) {
                        case 'nav_list':
                            $("#main-navlist").html(template(k, data));
                            break;
                        case 'adv_list':
                            $("#main-container1").html(template(k, data));
                            break;
                        case 'extral':
                            break;
                        default:
                            html += template(k, data);
                    }
                });

                $("#main-container2").html(html);

	            $( '.time-group').unbind().scroll(function () {
		            // 记录滚动条滚动的位置
		            var timeGroupObj = $('.time-group');
		            window.timePeriodScrollLeft = timeGroupObj.scrollLeft();
	            });

	            window.timePeriodReset = true;
                // 初始化商品时段
                timePeriodInit();

                $('.adv_list').each(function() {
                    if ($(this).find('.item').length < 2) {
                        $(this).find('.swipe-nav').hide();
                        return;
                    }

                    Swipe(this, {
                        speed: 400,
                        auto: 3000,
                        continuous: true,
                        disableScroll: false,
                        stopPropagation: false,
                        callback: function(index, elem) {
                            $(elem).parents('.adv_list').find('.swipe-nav em').removeClass('active');
                            $(elem).parents('.adv_list').find('.swipe-nav em').eq(index).addClass('active');
                        },
                        transitionEnd: function(index, elem) {}
                    });
                });
            }
        });
    }

    // 页面初始化
    pageLoad();

    // 页面数据重新加载
    window.pageReload = function () {
	    window.statusBarResetDisabled = false;  // 允许重设头部
	    window.timePeriodReset = true;
	    window.notFirstLoad = false;
	    message();
	    // memberCheck();
        getCartCount();
	    timePeriodInit();
    };

    mui.init({
        keyEventBind: {
            backbutton: true //开启back按键监听
        }
    });
    mui.plusReady(function () {
    	getCurrentWindow().id = 'mall/index';
	    var StatusbarHeight = plus.navigator.getStatusbarHeight() || 20;
	    localCache('STATUS_BAR_HEIGHT', StatusbarHeight, 30);
	    $('.sctouch-home-top').css({
		    'padding-top': StatusbarHeight
	    });
	    plus.navigator.setStatusBarStyle('light');

        var tuichu = "再按一次退出程序";
        var backButtonPress = 0;

        // 关闭所有无用窗口
        clearAllWindows();
        mui.back = function(event) {
            backButtonPress++;
            if(backButtonPress > 1) {
                var main = plus.android.runtimeMainActivity();
                main.moveTaskToBack(false);
                return false;
            } else {
                plus.nativeUI.toast(tuichu);
            }
            setTimeout(function() {
                backButtonPress = 0;
            }, 1000);
            return false;
        };
        
	    //仅支持竖屏显示  
	    plus.screen.lockOrientation("portrait-primary");  
	
	    document.addEventListener("newintent", function() {
            mui.toast('消息点击触发');
	        openWebviewFromOthers();
	    });

	    plus.push.addEventListener("click", function(msg) {
            mui.toast('点击');
	        console.log("push click");
	        pushGetRun(msg.payload);
	    }, false);
	    plus.push.addEventListener("receive", function(msg) {
	        mui.toast('接收消息提醒');
	        //获取透传数据
	        var data = JSON.parse(msg.payload);
	        //创建本地消息
	        plus.push.createMessage(data.content, data.payload, {
	           title: data.title,
	           cover: false
	        });
	    }, false);
        openWebviewFromOthers();
	});  
	function pushGetRun(payload) {  
	    payload = JSON.parse(payload);  
	    var id = payload.id;  
	    var autoShow = payload.autoshow;  
	    var event = payload.event;  
	    var params = JSON.stringify(payload.params);  
	    //用参数打开指定页面   ......
	}  
	//获取通知栏（app未启动）点击、第三方程序启动本app  
	function openWebviewFromOthers() {  
	    var args = plus.runtime.arguments;  
	    if(args) {  
	        pushGetRun(args);  
	    }  
	}
	$(document).on();
});

